<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/18
 * Time: 14:04:11
 */

namespace Service\WebSocketService;

use App\Model\BbcModel\GoodsAggregation;
use App\Model\BbcModel\GoodsAggregationGoods;
use Service\Code\Normal;
use Service\ExportService\ExportExcelHandle;

class AggregationGoodsService extends BaseWsService
{
    /**
     * 聚合商品导出
     * @param $server
     * @param int $fd
     * @param array $body
     * @param int $manager_id
     * @param int $cid
     * @return array
     */
    public function export($server, int $fd, array $body, int $manager_id, int $cid)
    {
        ini_set('memory_limit', '3096M');
        $param        = $body;
        $param['cid'] = $cid;

        $whereRaw = (new \Service\CommodityService\AggregationGoodsService())->makeWhere($param);
        if ($server) {
            $send = Normal::returnCode(Normal::WS_START, "进行中", [
                'percent' => 20,
            ]);
            $server->push($fd, json_encode($send, JSON_UNESCAPED_UNICODE));
        }

        $data_list = GoodsAggregation::instance()
            ->where($whereRaw)
            ->select(['id','name','show_name','cd'])
            ->get()->toArray();

        if(!$data_list){
            return Normal::returnCode(Normal::WS_ERROR,'数据为空');
        }

        foreach ($data_list as &$v){
            $goods_list = GoodsAggregationGoods::instance()
                ->leftJoin('ly_goods','ly_goods.id','=','ly_goods_aggregation_goods.goods_id')
                ->where(['ly_goods_aggregation_goods.aggregation_id'=>$v['id'],'df'=>0,'ly_goods.df'=>0])
                ->pluck('num_storage')->toArray();
            $v['sku_num'] = count($goods_list);

            $v['num_storage'] = array_sum($goods_list);

            $v['cd'] = date('Y-m-d H:i:s',$v['cd']);
        }

        $data['header'] = [
            'id', '聚合商品名称', '显示名称','创建时间','商品sku数','商品总库存',
        ];

        $data['fileName'] = '聚合商品.xlsx';
        $data['data']     = $data_list;
        $exportRes        = ExportExcelHandle::instance()->uploadAliOssSource($data['fileName'], $data['header'], $data['data']);
        if ($exportRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::WS_ERROR, '导出失败:' . $exportRes['msg']);
        }
        return Normal::returnCode(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $exportRes['data']['path'],
        ]);
    }
}